﻿
using CNative.WebApi.Common;
using CNative.WebApi.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace CNative.WebApiHost
{
    public partial class Service : ServiceBase
    { 
        #region Service
        public Service(IBootstrap _bootstrap)
        {
            InitializeComponent();

            this.CanHandlePowerEvent = true;
            //this.CanPauseAndContinue = true;
            this.CanShutdown = true;
            this.CanStop = true;
            this.AutoLog = true;

            this.ServiceName = MyProgram.ServiceName;
            this.Description = MyProgram.Description;

            bootstrap = _bootstrap;
        }
        #region Description
        string description = "";
        /// <summary>
        /// 服务描述
        /// </summary>
        public string Description
        {
            get
            {
                return description + "(" + this.ServiceName + ".exe)"; ;
            }
            set { description = value; }
        }
        #endregion
        #endregion

        #region OnStart
        /// <summary>
        /// 设置具体的操作，以便服务可以执行它的工作。
        /// </summary>
        protected override void OnStart(string[] args)
        {
            bootstrap.Start();
        }
        #endregion

        #region OnStop
        /// <summary>
        /// 停止此服务。
        /// </summary>
        protected override void OnStop()
        {
            bootstrap.Stop();
        }
        #endregion
        #region Service other Events
        #region CloseCurrentProcess
        public static void CloseCurrentProcess()
        {
            CloseCurrentProcess(false);
        }
        /// <summary>
        ///  Boolean : judgement current program is running
        /// </summary>
        /// <returns></returns>
        public static void CloseCurrentProcess(bool IsAll)
        {
            try
            {
                //			this.Close();
                Process currentProcess = Process.GetCurrentProcess(); //获取当前进程 
                //获取当前运行程序完全限定名 
                //string currentFileName = currentProcess.MainModule.FileName; 
                string currentModuleName = currentProcess.MainModule.ModuleName;
                //获取进程名为ProcessName的Process数组。 
                Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);
                //遍历有相同进程名称正在运行的进程 
                foreach (Process process in processes)
                {
                    try
                    {
                        if (IsAll || process.Id == currentProcess.Id)
                        { //根据进程ID排除当前进程 
                            process.Kill();
                        }
                    }
                    catch { }
                }
            }
            catch { }
        }
        #endregion
        #region OnShutdown
        /// <summary>
        /// OnShutdown(): Called when the System is shutting down
        /// - Put code here when you need special handling
        ///   of code that deals with a system shutdown, such
        ///   as saving special data before shutdown.
        /// </summary>
        protected override void OnShutdown()
        {
            CloseCurrentProcess(); // OnStop();
        }
        #endregion

        #region OnPause
        /// <summary>
        /// OnPause: Put your pause code here
        /// - Pause working threads, etc.
        /// </summary>
        protected override void OnPause()
        {
            OnStop();
        }
        #endregion

        #region OnContinue
        /// <summary>
        /// OnContinue(): Put your continue code here
        /// - Un-pause working threads, etc.
        /// </summary>
        protected override void OnContinue()
        {
            try
            {
                OnStart(new string[0]);
            }
            catch (Exception ex) { LogUtil.Error(ex.ToString()); }
        }
        #endregion

        #region OnCustomCommand
        /// <summary>
        /// OnCustomCommand(): If you need to send a command to your
        ///   service without the need for Remoting or Sockets, use
        ///   this method to do custom methods.
        /// </summary>
        /// <param name="command">Arbitrary Integer between 128 & 256</param>
        protected override void OnCustomCommand(int command)
        {
            //  A custom command can be sent to a service by using this method:
            //#  int command = 128; //Some Arbitrary number between 128 & 256
            //#  ServiceController sc = new ServiceController("NameOfService");
            //#  sc.ExecuteCommand(command);

            try
            {

            }
            catch (Exception ex) { LogUtil.Error(ex.ToString()); }
        }
        #endregion

        #region OnPowerEvent
        /// <summary>
        /// OnPowerEvent(): Useful for detecting power status changes,
        ///   such as going into Suspend mode or Low Battery for laptops.
        /// </summary>
        /// <param name="powerStatus">The Power Broadcast Status
        /// (BatteryLow, Suspend, etc.)</param>
        protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus)
        {
            try
            {
                //powerStatus.CompareTo(PowerBroadcastStatus.
            }
            catch (Exception ex) { LogUtil.Error(ex.ToString()); }
            return base.OnPowerEvent(powerStatus);
        }
        #endregion
        #endregion

        #region 变量
        protected IBootstrap bootstrap = null;
        #endregion

    }
}
